<?php
include_once('config/config.php');

$admin = LoginCheck();

$id = $_GET['id'] ?? 0;

$person = find("SELECT * FROM `pre_person` WHERE `id` = '$id'");

// 根据员工选择的地区获取相应地区数据
$province = find("SELECT * FROM `pre_region` WHERE `code` = '{$person['province']}'");
$city = find("SELECT * FROM `pre_region` WHERE `code` = '{$person['city']}'");
$district = find("SELECT * FROM `pre_region` WHERE `code` = '{$person['district']}'");

if (!$person) {
  notice('员工不存在');
}

if ($_POST) {
  $name = isset($_POST['name']) ? trim($_POST['name']) : '';
  $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
  $email = isset($_POST['email']) ? trim($_POST['email']) : '';
  $gender = isset($_POST['gender']) ? trim($_POST['gender']) : 0;
  $depid = isset($_POST['depid']) ? trim($_POST['depid']) : 0;
  $jobid = isset($_POST['jobid']) ? trim($_POST['jobid']) : 0;
  $code = isset($_POST['code']) ? trim($_POST['code']) : 0;
  $address = isset($_POST['address']) ? trim($_POST['address']) : 0;

  if (empty($name)) {
    notice('姓名不能为空');
  }

  if (empty($mobile)) {
    notice('手机号不能为空');
  }

  $mobileReg = "/^1[3-9]\d{9}$/";

  preg_match($mobileReg, $mobile, $res);

  if (!$res) {
    notice('手机号格式错误');
  }

  if (empty($email)) {
    notice('邮箱不能为空');
  }

  $dep = find("SELECT * FROM `pre_department` WHERE `id` = '$depid'");

  if (!$dep) {
    notice('部门不存在');
  }

  $job = find("SELECT * FROM `pre_job` WHERE `id` = '$jobid'");

  if (!$job) {
    notice('职位不存在');
  }

  if (empty($address)) {
    notice('详细地址不能为空');
  }

  // 封装数据
  $data = [
    'name' => $name,
    'mobile' => $mobile,
    'email' => $email,
    'gender' => $gender,
    'depid' => $depid,
    'jobid' => $jobid,
    'address' => $address
  ];

  $path = find("SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'");

  if (!$path) {
    notice('所选地区不存在');
  }

  $pathArr = explode(',', $path['parentpath']);

  $data['province'] = $pathArr[0] ?? null;
  $data['city'] = $pathArr[1] ?? null;
  $data['district'] = $pathArr[2] ?? null;

  if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
    $avatar = build_upload('avatar');

    if ($avatar['code'] === 0) {
      notice($avatar['msg']);
    }

    $data['avatar'] = $avatar['data'];
  }

  $result = update('person', $data, "`id` = '$id'");

  if ($result['code'] === 1) {
    if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
      @is_file('.' . $person['avatar']) && unlink('.' . $person['avatar']);
    }

    notice('修改成功', 'PersonList.php');
  } else {
    if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
      @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
    }

    echo $result['msg'];
    exit;
  }
}

// 查询部门数据
$DepSql = "SELECT * FROM `pre_department` ORDER BY `id` DESC";

$DepData = all($DepSql);

// 获取部门数据里的第一个部门
$depid = $DepData[0]['id'] ?? 0;

$JobSql = "SELECT * FROM `pre_job` WHERE `depid` = '{$person['depid']}' ORDER BY `id` DESC";

$JObData = all($JobSql);

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include_once('common/meta.php'); ?>
  <link rel="stylesheet" href="/assets/lib/city-picker/city-picker.css">

  <script src="/assets/lib/city-picker/city-picker.data.min.js"></script>
  <script src="/assets/lib/city-picker/city-picker.min.js"></script>
</head>
<style>
  #upload {
    width: 200px;
    height: 200px;
    object-fit: cover;
  }
</style>

<body>
  <?php include_once('common/header.php'); ?>

  <?php include_once('common/menu.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">添加员工</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">Home</a> <span class="divider">/</span></li>
      <li class="active">PersonAdd</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='PersonList.php'"><i class="icon-list"></i>
            员工列表
          </button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="post" enctype="multipart/form-data">
                <label>姓名</label>
                <input type="text" name="name" value="<?php echo $person['name']; ?>" class="input-xxlarge">

                <label>手机号</label>
                <input type="text" name="mobile" value="<?php echo $person['mobile']; ?>" class="input-xxlarge">

                <label>邮箱</label>
                <input type="email" name="email" value="<?php echo $person['email']; ?>" class="input-xxlarge">

                <label>性别</label>
                <select name="gender" class="input-xxlarge">
                  <option value="0" <?php echo $person['gender'] == 0 ? 'selected' : '' ?>>保密</option>
                  <option value="1" <?php echo $person['gender'] == 1 ? 'selected' : '' ?>>男</option>
                  <option value="2" <?php echo $person['gender'] == 2 ? 'selected' : '' ?>>女</option>
                </select>

                <label>部门</label>
                <select name="depid" id="depid" class="input-xxlarge">
                  <?php if ($DepData) { ?>
                    <?php foreach ($DepData as $item) { ?>
                      <option value="<?php echo $item['id']; ?>" <?php echo $person['depid'] == $item['id'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>
                    <?php } ?>
                  <?php } else { ?>
                    <option value="0">暂无部门</option>
                  <?php } ?>
                </select>

                <label>职位</label>
                <select name="jobid" id="jobid" class="input-xxlarge">
                  <?php if ($JObData) { ?>
                    <?php foreach ($JObData as $item) { ?>
                      <option value="<?php echo $item['id']; ?>" <?php echo $person['jobid'] == $item['id'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>
                    <?php } ?>
                  <?php } else { ?>
                    <option value="0">暂无职位</option>
                  <?php } ?>
                </select>

                <div style="position: relative;height:65px">
                  <label>地区选择</label>
                  <input type="text" id="region" data-toggle="city-picker" class="input-xxlarge">
                  <input type="hidden" name="code" id="code" value="<?php echo $person['district'] ? $person['district'] : ($person['city'] ? $person['city'] : $person['province']); ?>">
                </div>

                <label>详细地址</label>
                <input type="text" name="address" value="<?php echo $person['address']; ?>" class="input-xxlarge">

                <label>头像</label>
                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                <img src="<?php echo is_file('.' . $person['avatar']) ? $person['avatar'] : '/assets/images/upload.png' ?>" id="upload" onclick="avatar.click();" alt="">

                <label></label>
                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <?php include_once('common/footer.php'); ?>
      </div>
    </div>
  </div>

</body>

</html>

<script>
  // 头像预览
  $('#avatar').change(function() {
    // 获取上传文件
    let file = $(this)[0].files[0];

    if (file) {
      // 实例化一个读取本地文件的对象
      let Reader = new FileReader();

      // file对象转成base64编码 二进制文件流
      Reader.readAsDataURL(file);

      Reader.onload = function() {
        $('#upload').attr('src', Reader.result);
      }
    }

  })

  $("#region").on("cp:updated", function() {
    let citypicker = $(this).data("citypicker");
    let code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
    $("#code").val(code);
  });

  $('#region').citypicker('reset');
  $('#region').citypicker('destroy');


  $('#region').citypicker({
    province: `<?php echo $province['name'] ?>`,
    city: `<?php echo $city['name'] ?>`,
    district: `<?php echo $district['name'] ?>`
  });

  $('#depid').change(function() {
    let depid = $(this).val();

    $.ajax({
      type: 'post',
      url: 'api.php',
      data: {
        depid,
        action: 'job'
      },
      dataType: 'json',
      success: (res) => {

        let option = '';

        if (res.code === 1) {
          for (let item of res.data) {
            option += `<option value="${item.id}">${item.name}</option>`;
          }
        } else {
          option = `<option value="0">暂无职位</option>`
        }

        $('#jobid').html(option);

      }
    })
  })
</script>